package com.changgou.seckill.web.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.seckill.feign.SecKillOrderFeign;
import com.changgou.seckill.web.aspect.AccessLimit;
import com.changgou.seckill.web.util.CookieUtil;
import com.changgou.util.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/wseckillorder")
public class SecKillOrderController {

    @Autowired
    private SecKillOrderFeign secKillOrderFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 秒杀下单+秒杀下单接口隐藏
     * @param time
     * @param id
     * @param random
     * @return
     */
    @RequestMapping("/add")
    @AccessLimit//自定义注解完成限流
    public Result add(@RequestParam("time") String time, @RequestParam("id") long id, @RequestParam("ramndom") String random) {
        //对比随机字符串
        //1.从redis中获取随机字符串
        String cookieValue = this.readCookie();
        String redisRandom = (String) redisTemplate.opsForValue().get("randomcode_" + cookieValue);
        if (StringUtils.isEmpty(redisRandom)) {
            return new Result(false, StatusCode.ERROR, "redis随机字符串为空");
        }
        if (redisRandom.equals(random)) {
            return new Result(false, StatusCode.ERROR, "redis随机字符串和前端传来的随机字符串不一致");
        }

        Result result = secKillOrderFeign.add(time, id);
        return result;
    }

    /***
     * 生成随机数作为接口令牌, 有效期60秒
     * @return
     */
    @GetMapping("/getToken")
    public String getToken() {
        //1.获取随机字符串
        String randomString = RandomUtil.getRandomString();
        //2.获取jti
        String cookieValue = this.readCookie();
        //3.短令牌作为key, 随机字符串作为value
        redisTemplate.opsForValue().set("randomcode_" + cookieValue, randomString, 60, TimeUnit.SECONDS);
        //4.返回随机字符串
        return randomString;
    }

    private String readCookie() {
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Map<String, String> map = CookieUtil.readCookie(request, "uid");
        String jti = map.get("uid");
        return jti;
    }
}
